package com.hsnn.medstgmini.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @category 对外连接通用类
 * @author 单大伟
 * @date 2015-06-10
 */
public class ConnectionUtil {
	private transient static Log log = LogFactory.getLog(ConnectionUtil.class);

	/**
	 * @category 将传入的数据变为http参数的键值对格式
	 * @author 单大伟
	 * @date 2015-06-13
	 * @param map 要传送的数据
	 * @return String 键值对格式的http参数
	 */
	public static String mapToURLEncodeString(Map<String, String> map){
		if (map == null) {
			return null;
		} else if (map.size() == 0) {
			return "";
		}

		StringBuffer buffer = new StringBuffer();
		Set<String> keys = map.keySet();
		try{
			for(String key : keys){
				if(key == null){
					continue;
				}
				buffer.append(key).append("=");
				if (map.get(key) != null){
					buffer.append(URLEncoder.encode(map.get(key), "UTF-8"));
				}
				buffer.append("&");
			}
		} catch (UnsupportedEncodingException e) {
			log.error("Url encoding error.", e);
		}
		return buffer.substring(0, buffer.length()-1);
	}

	/**
	 * @category 将收到的http键值对格式的数据变为map
	 * @author 单大伟
	 * @date 2015-06-13
	 * @param String 键值对格式的http参数
	 * @return Map map键值对 
	 */
	public static Map<String, String> urlEncodeStringToMap(String response)throws Exception{
		HashMap<String, String> results = new HashMap<String, String>();
		String[] tokens = response.split("&");
		for (String token : tokens) {
			int index = token.indexOf('=');
			if (index != -1) {
				if (token.substring(index + 1) != null) {
					results.put(token.substring(0, index), URLDecoder.decode(token.substring(index + 1), "UTF-8"));
				}else{
					results.put(token.substring(0, index), "");
				}
			} else {
				log.info("Error parsing the token: " + token);
            }
		}
		return results;
	}

	/**
	 * @category 与外界进行http通讯
	 * @author 单大伟
	 * @date 2015-06-13
	 * @param String httpParams http请求
	 * @param String httpUrl    外界httpUrl
	 * @param String timeout    无响应时链接断开的时间
	 * @return String http响应
	 */
    public static String sendForProcessing(String httpParams, String httpUrl, String timeout) {
        String response = "";
        
        PrintWriter out = null;
        java.io.InputStream in = null;
        java.net.HttpURLConnection connection = null;
        
        try {
            log.info("Sending to URL: " + httpUrl + " Time out setting: " + timeout);
            java.net.URL url = new java.net.URL(httpUrl);
            connection = (java.net.HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            int timeoutMillis = Integer.valueOf(timeout);
            connection.setConnectTimeout(timeoutMillis);
            connection.setReadTimeout(timeoutMillis);
            connection.connect();
            
            // Do output
            out = new java.io.PrintWriter(connection.getOutputStream());
            out.print(httpParams);
            out.flush();
            
            // Read
            in = connection.getInputStream();
            java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(in));
            response = reader.readLine();
        } catch (IOException e) {
            log.error("IOException.", e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("encounter IOException during closing InputStream! ", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response;
    }
}